<template>
  <div class="club-top-component">
    <el-row type="flex" justify="space-around" align="middle">

      <el-col :span="8">
        <el-button type="primary" v-if="!participationState" class="big-button" @click="applyJoin" :disabled="isAdmin" :title="isAdmin ? '系统管理员无法执行此操作' : ''">
          <i class="el-icon-user"></i> 申请加入
        </el-button>

        <el-button type="primary"  v-else class="big-button" @click="quitClub">
          <i class="el-icon-user"></i> 退出社团
        </el-button>

      </el-col>

      <el-col :span="8">
        <el-button type="success" v-if="!favoriteState" class="big-button" @click="toggleFavorite" :disabled="isAdmin" :title="isAdmin ? '系统管理员无法执行此操作' : ''">
          <i class="el-icon-star-off"></i> 点击收藏
        </el-button>

        <el-button type="success" v-else class="big-button" @click="openCancel">
          <i class="el-icon-star-on"></i> 取消收藏
        </el-button>
      </el-col>

      <el-col :span="8">
        <el-button type="warning" class="big-button" @click="navigateToCommunity" :disabled="isAdmin" :title="isAdmin ? '系统管理员无法执行此操作' : ''">
          <i class="el-icon-chat-dot-round"></i> 进入社区
        </el-button>
      </el-col>

    </el-row>
  </div>
</template>

<script>
import {ElButton, ElRow, ElCol, ElMessageBox, ElIcon, ElMessage} from 'element-plus';
import axios from 'axios'
export default {
  name: 'ClubTopComponent',
  data(){
    return{
      userType: '',
      participationState:false,
      favoriteState:false,
      clubPosition:null
    }
  },
  props: {
    club: {
      type: Object,
      required: true
    }
  },
  components: {
    ElButton,
    ElRow,
    ElCol,
    ElIcon
  },
  async created() {
    this.getState();

    const temp=sessionStorage.getItem("token");
    if(temp!=null&&temp!==""){
      try {
        const response = await axios.get("/user/getUserType");
        if (response.data.code === 0) {
          this.userType = response.data.data;
        } else {
          console.error('获取用户类型失败:', response.data.message);
        }
      } catch (error) { console.error('获取用户类型时发生错误:', error); }
    }

  },


  computed: {
    isAdmin() {
      return this.userType === '系统管理员';
    }
  },
  methods: {

    getState(){
      let params = {
        clubId: this.club.clubId,
        studentId:sessionStorage.getItem("studentId")
      }

      // const token=sessionStorage.getItem("token");
      // if (token !== null && token !== "") {
      //   axios.get("/participation/clubPosition", { params: {
      //     clubId: this.club.clubId
      //   } })
      //     .then(response => {
            
      //       const result=response.data.data;
      //       if(result==="非成员"){
      //         this.participationState = false;
      //       } else {
      //         // this.clubPosition=response.data.data;
      //         this.clubPosition="退出社团";
      //         this.participationState = true;
      //       }
      //     })
      //     .catch(error => {
      //       console.log(error);
      //     })
      // }

      axios.get("/participation/ParticipationState", { params })
        .then(response => {
          this.participationState = response.data.data;
        })
        .catch(error => {
          console.log(error);
        })

      axios.get("/favorite/favoriteState",{params})
        .then(response => {
          this.favoriteState=response.data.data;
        })
        .catch(error => {
          console.log(error);
        })
    },


    applyJoin() {
      ElMessageBox.confirm(
          '确定要申请加入社团吗？',
          '申请加入',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        console.log('加入社团');
        try {
          const response=await axios.post('/application/joinClub', null, {params: {clubId: this.club.clubId}});
          if(response.data.data==="已接受"){
            this.$message.error('你已经在社团里面了喔');
          }
          else{
            this.$message.success('申请已提交！');
          }
          this.getState();
        } catch (error) {
          console.error("Error fetching footprints:", error);
        }
      }).catch(() => {
        console.log('取消申请');
      });
    },

    async quitClub(){
      ElMessageBox.confirm(
          '确定要退出社团吗？',
          '退出社团',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          const response=await axios.post('/club/quitClub', null, {params: {clubId: this.club.clubId}});
          if(response.data.code===0){
            this.$message.success('已退出社团');
          }
          else{
            ElMessage({
              message: response.data.message||'退出社团失败',
              type: 'error',
              showClose:true
            })
          }
          this.getState();
        } catch (error) {
          console.error("Error quiting club:", error);
          ElMessage({
            message: error.data.message,
            type: 'error',
            showClose:true
          })

          this,this.getState()
        }
      }).catch(() => {
        console.log('取消操作');
      });
    },
    async toggleFavorite() {
      try {
        await axios.post('/favorite/favoriteNewClub', null, {params: {clubId: this.club.clubId}});
        ElMessageBox.alert('收藏成功', '提示', {
          confirmButtonText: '确定',
          type: 'success',
          center: true
        }).catch(() => {
          console.log('关闭提示框');
        });

        this.favoriteState=true;
      } catch (error) {
        if (error.response && error.response.status !== 401) {
          ElMessageBox.alert('收藏失败', '提示', {
            confirmButtonText: '确定',
            type: 'error',
            center: true
          }).catch(() => {
            console.log('关闭提示框');
          });
        }
      }
    },

    openCancel(){
      ElMessageBox.confirm(
        '你确认取消收藏吗?',
        {
          confirmButtonText: 'YES',
          cancelButtonText: 'NO',
          center:true,
          roundButton:true
        }
      )
        .then(() => {
          this.cancelFavorite();
        })
        .catch(() => {

        })
    },

    cancelFavorite(){
      axios.post('/favorite/cancelFavorite', null, { params: { clubId: this.club.clubId } })
        .then(() => {
          ElMessageBox.alert('取消收藏成功', '提示', {
            confirmButtonText: '确定',
            type: 'success',
            center: true
          }).catch(() => {
            console.log('关闭提示框');
          });

          this.favoriteState = false;
      })
      .catch(error => {
        ElMessageBox.alert('取消收藏失败', '提示', {
          confirmButtonText: '确定',
          type: 'error',
          center: true
        }).catch(() => {
          console.log('关闭提示框');
        });
      });
    },

    navigateToCommunity() {
      const clubId = this.club.clubId;
      this.$router.push({ name: "CommunityDetail", query: { clubId: clubId } });
    }
  }
};
</script>


<style scoped>
.club-top-component {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.el-row {
  width: 100%;
  margin: 0 !important;
}

.el-col {
  display: flex;
  justify-content: center;
  align-items: center;
}

.big-button {
  font-size: 18px;
  padding: 10px 15px;
  width: 90%;
  max-width: 200px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  transition: all 0.3s;
  border: none;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-weight: 600;
  color: #FFFFFF;
}

.big-button i.el-icon {
  font-size: 24px;
  margin-right: 10px;
}

/* 按钮颜色 */
.el-button--primary {
  background-color: #FFC107;
}

.el-button--success {
  background-color: #FFB300;
}

.el-button--warning {
  background-color: #FF9800;
}

.big-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.el-button--primary:hover {
  background-color: #FFD54F;
}

.el-button--success:hover {
  background-color: #FFA000;
}

.el-button--warning:hover {
  background-color: #F57C00;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .big-button {
    font-size: 16px;
    padding: 8px 12px;
    height: 50px;
    max-width: none;
  }

  .big-button i.el-icon {
    font-size: 20px;
    margin-right: 8px;
  }
}
</style>
